import { Form, Input, Checkbox, Button, Space } from '@arco-design/web-react';
import { FormInstance } from '@arco-design/web-react/es/Form';
import React, { useContext, useEffect, useRef, useState } from 'react';
import useStorage from '@/utils/useStorage';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import styles from './style/index.module.less';
import { Login } from '@/api/modules';
import store from '@/store';
import { useHistory } from 'react-router-dom';
import { IconEye, IconEyeInvisible } from '@arco-design/web-react/icon';
import { GlobalContext } from '@/context';

export default function LoginForm() {
  const { rtl } = useContext(GlobalContext);
  const formRef = useRef<FormInstance>();
  const [loading, setLoading] = useState(false);
  function encryptData(data) {
    return btoa(data);
  }

  // 解密函数
  function decryptData(encryptedData) {
    return atob(encryptedData);
  }
  const [loginParams, setLoginParams] = useStorage('iuykuykyjty');

  const t = useLocale(locale);
  const history = useHistory();
  function afterLoginSuccess(params: { username: any; password: any }) {
    // 记住密码

    // setLoginParams(encryptData(JSON.stringify(params)));

    // 跳转首页

    history.replace('/');
  }

  // 树状数据扁平化
  const getTableData = (data, parentName = '') => {
    return data.reduce(
      (
        arr = [],
        {
          id = '',
          name = '',
          type = '',
          url = '',
          children = [],
          checked = false,
        }
      ) => {
        const newName = url && url.replace(/\s/g, '').toLowerCase();
        return arr.concat(
          [
            {
              id,
              type,
              url,
              name: newName,
              children,
              parentName,
              checked,
              code: name,
            },
          ],
          getTableData(children || [], newName)
        );
      },
      []
    );
  };

  function login(e) {
    setLoading(true);
    console.log(e);
    const params = {
      username: e.username.trim().toLowerCase(),
      password: e.password.trim(),
    };
    Login(params)
      .then((res) => {
        setLoading(false);
        const { token } = res.data;
        const meuns = new Set();
        const actions = new Set();
        if (res.data.menus) {
          const arr = getTableData(res.data.menus);
          arr.forEach((a) => {
            if (!!a.url) {
              if (a.type !== 'MENU' && a.checked) {
                const name = a.url;
                meuns.add(name.toLowerCase());
              }

              // 按钮操作权限，code就是URL
              if (a.type !== 'MENU' && a.checked) {
                const name = (a.parentName ? a.parentName + '.' : '') + a.name;
                actions.add(name);
              }
            }
          });
        }
        store.dispatch({ type: 'update-token', payload: { token: token } });
        store.dispatch({
          type: 'update-meunsAndActions',
          payload: {
            meuns: Array.from(meuns),
            actions: Array.from(actions),
            roles: res.data.roles,
          },
        });
        store.dispatch({
          type: 'update-userInfo',
          payload: { userInfo: res.data },
        });
        afterLoginSuccess(params);
      })
      .catch(() => {
        setLoading(false);
      });
  }

  function onSubmitClick() {
    formRef.current.validate().then((values) => {
      login(values);
    });
  }

  // 读取 localStorage，设置初始值
  useEffect(() => {
    // if (formRef.current && !!loginParams) {
    //   const parseParams = JSON.parse(decryptData(loginParams));
    //   formRef.current.setFieldsValue(parseParams);
    // }
  }, [loginParams]);

  const [inputType, setInputType] = useState<string>('password');

  return (
    <div className={styles['login-form-wrapper']}>
      <div className={styles['login-form-title']}>{t['login.form.title']}</div>
      <Form className={styles['login-form']} layout="vertical" ref={formRef}>
        <Form.Item
          field="username"
          rules={[{ required: true, message: t['login.form.userName.errMsg'] }]}
        >
          <Input
            placeholder={t['login.form.userName.placeholder']}
            onPressEnter={onSubmitClick}
            className={styles['input']}
          />
        </Form.Item>

        <label style={{ position: 'relative' }}>
          <Form.Item
            field="password"
            rules={[
              { required: true, message: t['login.form.password.errMsg'] },
            ]}
          >
            <Input
              type={inputType}
              placeholder={t['login.form.password.placeholder']}
              onPressEnter={onSubmitClick}
              className={styles['input']}
            />
          </Form.Item>
          <div
            style={{
              position: 'absolute',
              top: 0,
              right: 0,
              height: '100%',
              display: 'flex',
              alignItems: 'center',
              paddingRight: '12px',
              paddingLeft: '12px',
              cursor: 'pointer',
              color: '#000',
              paddingBottom: '20px',
            }}
            onClick={(e) => {
              e.stopPropagation();
              setInputType(inputType == 'password' ? 'text' : 'password');
            }}
          >
            {inputType == 'password' ? <IconEyeInvisible /> : <IconEye />}
          </div>
        </label>

        <Space align="center" direction="vertical">
          <Button
            type="primary"
            long
            onClick={onSubmitClick}
            loading={loading}
            className={styles['login-form-button']}
          >
            {t['login.form.login']}
          </Button>
        </Space>
      </Form>
    </div>
  );
}
